package org.safaproject.safa;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;

import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.form.AjaxFormSubmitBehavior;
import org.apache.wicket.extensions.ajax.markup.html.autocomplete.AutoCompleteTextField;
import org.apache.wicket.markup.html.WebPage;
import org.apache.wicket.markup.html.basic.Label;
import org.apache.wicket.markup.html.form.Form;
import org.apache.wicket.model.Model;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.apache.wicket.util.string.Strings;
import org.safaproject.safa.entities.Tag;
import org.safaproject.safa.services.TagsService;

public class BasePage extends WebPage {
	
	@SpringBean(name="tagsService")
	private TagsService tagsService;

	@SuppressWarnings("serial")
	public BasePage() {
		final List<Tag> tags = tagsService.getAllTags();
		Form<Void> searchForm = new Form<Void>("searchForm");
		add(searchForm);

		final AutoCompleteTextField<String> field = new AutoCompleteTextField<String>(
				"search", new Model<String>("")) {
			@Override
			protected Iterator<String> getChoices(String input) {
				if (Strings.isEmpty(input)) {
					List<String> emptyList = Collections.emptyList();
					return emptyList.iterator();
				}

				List<String> choices = new ArrayList<String>(10);
				
				for (Tag tag : tags) {
					if (tag.getValor().toUpperCase().startsWith(input.toUpperCase())) {
						choices.add(tag.getValor());
					}
					
					if (choices.size() == 10) {
						break;
					}
				}

				return choices.iterator();
			}
		};
		
		searchForm.add(field);

		final Label label = new Label("selectedValue", field.getDefaultModel());
		label.setOutputMarkupId(true);
		searchForm.add(label);

		field.add(new AjaxFormSubmitBehavior(searchForm, "onchange") {
			@Override
			protected void onSubmit(AjaxRequestTarget target) {
				target.addComponent(label);
			}

			@Override
			protected void onError(AjaxRequestTarget target) {
			}
		});
	}

	public void setTagsService(TagsService tagsService) {
		this.tagsService = tagsService;
	}

	public TagsService getTagsService() {
		return tagsService;
	}
}